package com.bxx.shiro;

import com.bxx.entity.User;
import com.bxx.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    /**
     * 执行授权逻辑
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行授权逻辑");
        return null;
    }

    /**
     * 执行认证逻辑
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行认证逻辑");

        // 假设数据库的用户名和密码
        String name = "bxx";
        String password = "123";

        // 编写 shiro 判断逻辑，判断用户名和密码

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;  //获取用户名密码信息

        User user = userService.findByUsername(token.getUsername());
        // 1.判断用户名
        if(user==null){
            return null; //shiro 底层会抛出 UnKnowAccountException
        }

        // 2.判断密码
        return new SimpleAuthenticationInfo("",user.getPassword(),"");
    }
}
